<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\BaseController;
use App\Jobs\DeleteStar;
use App\Models\Category;
use App\Models\HoneyBalance;
use App\Models\Material;
use App\Models\Order;
use App\Models\Star;
use App\Models\User;
use App\Models\Work;
use App\Services\HoneyBalanceService;
use App\Services\NotifyService;
use App\Services\OrderService;
use Dingo\Api\Http\Request;

class MaterialController extends BaseController
{

    public $model = Material::class;
    /**
     * 列表
     * @param Request $request
     * @return mixed
     */
    public function index(Request $request) {
        $title = $request->input('title');
        $category_id = $request->input('category_id');
        $parent_category_id = $request->input('parent_category_id');
        $audit_status = $request->input('audit_status', -1);
        $start_at = $request->input('start_at');
        $end_at = $request->input('end_at');
        $nickname = $request->input('nickname');
        $order_by_key = $request->input('order_by_key', 'sort');
        $order_by_value = $request->input('order_by_value', 'desc');

        $fields = '*';
        $list = Material::select($fields)->title($title)
            ->when($nickname, function ($q) use($nickname){
                $q->whereHas('user', function ($qt) use($nickname){
                    $qt->where('nickname', 'like', '%' . $nickname . '%');
                });
            })
            ->startAt($start_at)
            ->endAt($end_at)
            ->auditStatus($audit_status)
            ->category($category_id)
            ->parentCategory($parent_category_id)
            ->withCertain('user', ['nickname', 'avatar_url'])
            ->withCertain('category', ['title'])
            ->withCertain('parent_category', ['title']);

        $list = $list->orderBy($order_by_key, $order_by_value)->orderBy("id", "desc")
            ->paginate(\request('per_page', 20));

        return $this->paginate($list);
    }


    public function destroy(Request $request) {
        $this->validate($request, [
            'ids' => 'required'
        ]);
        $ids = $request->input('ids');
        $arr_id = explode(",", $ids);

        foreach ($arr_id as $id) {
            $model = $this->model::find($id);
            if ($model) {
                if ($model->audit_status == 1)
                    HoneyBalanceService::store($model->user_id, -HoneyBalance::POINT_MATERIAL, HoneyBalance::TYPE_MATERIAL, $model->id, true);

                $user_id = $model->user_id;
                $user = User::find($user_id);
                if ($user->material_count)
                    $user->increment('material_count', -1);

                $model->delete();
                dispatch(new DeleteStar(Star::TYPE_MATERIAL, $id, $user_id));
            }
        }
        return $this->success([]);
    }

    public function editStatus(Request $request) {
        $this->validate($request, [
            'ids' => 'required',
            'value' => 'required',
            'action' => 'required'
        ]);
        $value = \request('value');
        $action = \request('action');
        $reason = \request('reason', '');
        $ids = $request->input('ids');
        $arr_id = explode(",", $ids);

        $list = $this->model::whereIn('id', $arr_id)->get();
        $old_status = 0;
        foreach ($list as $item) {
            if ($action == 'audit') {
                $old_status = $item->audit_status;
                $item->audit_status = $value;
            } elseif ($action == 'black') {
                $item->is_black = $value;
            } elseif ($action == 'vip') {
                $item->is_vip = $value;
            } else if($action == 'sort') {
                $item->sort = $value;
            }
            if ($item->save()) {
                if (method_exists($this, '_after_editStatus')) {
                    $this->_after_editStatus($item, $action, $value, $reason, $old_status);
                }
            }
        }
        return $this->success([]);
    }

    public function _after_editStatus($item, $action, $value, $reason, $old_status) {
        if ($action == 'audit') {
            if ($value == 2) {
                $title = $item->title . "素材审核不通过";
                $reason = '尊敬的痕迹网用户您好，您的素材"'.$item->title.'"因"'.$reason.'"而审核不通过，请修改后再次提交审核';
                NotifyService::storeSystem($item->user_id, $title, $reason);
            } else if($value == 1) {
                //判断是否赠送
                $exists = HoneyBalance::where('entity_id', $item->id)->where('type', HoneyBalance::TYPE_MATERIAL)->where('user_id', $item->user_id)->exists();
                if (!$exists)
                    HoneyBalanceService::store($item->user_id, HoneyBalance::POINT_MATERIAL, HoneyBalance::TYPE_MATERIAL, $item->id, true);
            }
        }
    }


    public function order(Request $request)
    {
        $order_sn = $request->input('order_sn');
        $category_id = $request->input('category_id');
        $start_at = $request->input('start_at');
        $end_at = $request->input('end_at');

        $list = Order::where('entity_type', Order::ENTITY_MATERIAL)->where('status', Order::PAID_SUCCESS)->startAt($start_at)->endAt($end_at)
            ->orderSn($order_sn)
            ->when($category_id, function ($q) use($category_id){
                $q->where('category_id', $category_id);
            })
            ->withCertain('material', ['title', 'image_file', 'video_file'])
            ->withCertain('category', ['title'])
            ->withCertain('user', ['nickname', 'avatar_url'])
            ->withCertain('publish_uer', ['nickname', 'avatar_url'])
            ->orderBy("id", "desc")
            ->paginate(\request('per_page', 20));

        $extra['cash'] = OrderService::getMaterialCashAmount();
        $extra['honey'] = OrderService::getMaterialHoneyAmount();
        return $this->paginate($list, $extra);
    }

}

